package com.corticon.client.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.corticon.client.model.DialogRequestInput;
import com.corticon.client.model.NavigatePageInput;

public class CorticonApiService {
	private static String webServerUrl;
	private static String dialogRequest;
	private static String navigatePage;
	private static String dialogReport;
	private static String processResponse;
	protected static Log performancelogger = LogFactory.getLog("performance");

	public String getWebServerUrl() {
		return webServerUrl;
	}

	public void setWebServerUrl(String webServerUrl) {
		this.webServerUrl = webServerUrl;
	}

	public String getDialogRequest() {
		return dialogRequest;
	}

	public void setDialogRequest(String dialogRequest) {
		this.dialogRequest = dialogRequest;
	}

	public String getNavigatePage() {
		return navigatePage;
	}

	public void setNavigatePage(String navigatePage) {
		this.navigatePage = navigatePage;
	}

	public String getDialogReport() {
		return dialogReport;
	}

	public void setDialogReport(String dialogReport) {
		this.dialogReport = dialogReport;
	}

	public String getProcessResponse() {
		return processResponse;
	}

	public void setProcessResponse(String processResponse) {
		this.processResponse = processResponse;
	}
	
	public String postServerUrl(Object obj,String postMethod) throws IOException, Throwable, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException{
		// Get and config the connection.		
		HttpURLConnection conn;
		URL requestServiceUrl = new URL(getWebServerUrl()+postMethod+"?"+covertParameter(obj));
		System.out.println(requestServiceUrl.toString());
		Date startTime = new Date();		
		conn = (HttpURLConnection) requestServiceUrl.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);		
		conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
		//conn.setRequestProperty("Content-Length", Integer.valueOf(requestServiceUrl.toString()));
		conn.setInstanceFollowRedirects(true);
		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		// Get the response.
		InputStream is = conn.getInputStream();
		String rc = IOUtils.toString(is);
		Date stopTime = new Date();		
		System.out.println(rc);
		return rc;
	}	
	public String postProcessResponseUrl(String questionData,String postMethod,String lastQuestionName) throws IOException, Throwable, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException{
		// Get and config the connection.		
		HttpURLConnection conn;
		URL requestServiceUrl = new URL(getWebServerUrl()+postMethod);
		System.out.println(requestServiceUrl.toString());
		//performancelogger.debug("[Q-"+lastQuestionName+"][T1][beginning]");
		conn = (HttpURLConnection) requestServiceUrl.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);		
		conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
		//conn.setRequestProperty("Content-Length", Integer.valueOf(requestServiceUrl.toString()));
		conn.setInstanceFollowRedirects(true);
		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		// Get the response.
		PrintWriter out = new PrintWriter(conn.getOutputStream());
		String name = "questionData="+URLEncoder.encode(questionData, "UTF-8"); 
		System.out.println(name);
        // send the encoded message
        out.println(name);
        out.close();
		InputStream is = conn.getInputStream();
		String rc = IOUtils.toString(is);
		//performancelogger.debug("[Q-"+lastQuestionName+"][T1][End]");
		return rc;
	}
	private String covertParameter(Object obj) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
		String Parameter = "";
		Field[] fields = obj.getClass().getFields();
		for (int i=0;i<fields.length;i++){
			String fileldName= fields[i].getName();
			Method getMethod = obj.getClass().getMethod("get"+fileldName.substring(0,1).toUpperCase()+fileldName.substring(1), new Class[]{});
			Object value = getMethod.invoke(obj, new Object[]{});
			value = value==null?"":value;
			if (i>0){
				Parameter+="&";
			}			
			Parameter += fields[i].getName()+"="+value.toString();
		}		
		return Parameter;
	}
}